//
//  KZRandomDistributionView.m
//  听说弱点强化训练
//
//  Created by 朱凯 on 2018/8/22.
//  Copyright © 2018年 盛超. All rights reserved.
//

#import "KZRandomDistributionView.h"

#import "KZVocabularyPackageModel.h"

@implementation KZRandomDistributionView

- (instancetype)init {
    
    if (self = [super init]) {
        
    }
    return self;
}
- (void)layoutSubviews {
    
    [super layoutSubviews];
    if (_vocabularys.count == 0) {
        return;
    }
    
    [self.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    
    NSArray *colors = @[
                        [UIColor colorWithR:244 g:187 b:72 a:1],    // 黄
                        [UIColor colorWithR:206 g:92 b:226 a:1],    // 紫
                        [UIColor colorWithR:242 g:194 b:224 a:1],   // 粉
                        [UIColor colorWithR:105 g:216 b:98 a:1],    // 绿
                        [UIColor colorWithR:88 g:138 b:238 a:1],    // 蓝
                        ];
    NSArray *distributionMaxCounts = @[@3, @4, @5];
    NSArray *distributionMaxWidths = @[@75, @60, @45];
    NSMutableArray *tempCounts = [@[@0, @0, @0] mutableCopy];
    CGFloat interval = 15;
    for (int i = 0; i < _vocabularys.count; i ++) {
        
        KZVocabularyCurrentPackageDetailModel *model = _vocabularys[i];
        
        UIControl *gradientView = [UIControl new];
        [gradientView addTarget:self action:@selector(touchAction:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:gradientView];
        
        
        CGFloat width = arc4random_uniform(15)+30;
        NSInteger tag = 0;
        while (tag < distributionMaxCounts.count) {
            if ([tempCounts[tag] intValue] >= [distributionMaxCounts[tag] intValue]) {
                tag ++;
                continue;
            } else {
                width = arc4random_uniform(interval)+[distributionMaxWidths[tag] intValue];
                tempCounts[tag] = @([tempCounts[tag] intValue] + 1);
                break;
            }
        }
        NSLog(@"%.0lf", width);
        gradientView.layer.cornerRadius = width / 2;
        gradientView.layer.masksToBounds = true;
        gradientView.width = width;
        gradientView.height = width;
        gradientView.left = arc4random_uniform(self.width - width);
        gradientView.top = arc4random_uniform(self.height - width);
        __block BOOL isPositionOk = false;
        __block int times = 0;
        // 找到合适的位置存放视图
        do {
            __block BOOL intersects = false;
            
            [self.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                if (gradientView != obj) {
                    if (CGRectIntersectsRect(gradientView.layer.frame, obj.layer.frame)) {
                        
                        gradientView.left = arc4random_uniform(self.width - width);
                        gradientView.top = arc4random_uniform(self.height - width);
                        *stop = true;
                        intersects = true;
                        times ++;
                    };
                }
               
            }];
        
            if (intersects) {
                if (times < 100) {
                    continue;
                } else {
                    isPositionOk = true;
                }
                continue;
            } else {
                isPositionOk = true;
            }
        } while (!isPositionOk);
        
        // 渐变图层
        CAGradientLayer *gradientLayer = [CAGradientLayer layer];
        gradientLayer.bounds = CGRectMake(0, 0, width, width);
        gradientLayer.position = CGPointMake(width/2, width/2);
        UIColor *color = colors[i%colors.count];
        gradientLayer.colors = @[
                                 (__bridge id)[[UIColor whiteColor] colorWithAlphaComponent:0.9].CGColor,
                                 (__bridge id)[color colorWithAlphaComponent:0.8].CGColor,
                                 ];
        gradientLayer.locations = @[@0.05];
        [gradientView.layer insertSublayer:gradientLayer atIndex:0];
        
        // 文字
        UILabel *label = [[UILabel alloc] init];
        label.frame = CGRectMake(3, 0, gradientView.width - 6, gradientView.height);
        label.adjustsFontSizeToFitWidth = true;
        label.numberOfLines = 1;
        label.text = model.Vocabulary;
        label.font = FONT(16);
        label.textAlignment = NSTextAlignmentCenter;
        label.textColor = [UIColor whiteColor];
        [gradientView addSubview:label];
        NSShadow *shadow = [NSShadow new];
        shadow.shadowColor = [UIColor.blackColor colorWithAlphaComponent:0.8];
        shadow.shadowOffset = CGSizeMake(0, 1);
        shadow.shadowBlurRadius = 3;
        label.attributedText = [[NSAttributedString alloc] initWithString:label.text attributes:@{NSShadowAttributeName: shadow, NSVerticalGlyphFormAttributeName: @1}];
        
       
    }
    
    [self addAnimation];
    
}

- (void)setVocabularys:(NSArray *)vocabularys {
    
    _vocabularys = vocabularys;
    [self setNeedsLayout];
    [self layoutIfNeeded];
}

- (void)addAnimation {
    
    [self.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        CAKeyframeAnimation *keyAni = [CAKeyframeAnimation animationWithKeyPath:@"transform"];
        keyAni.duration = 0.8;
        keyAni.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
        keyAni.repeatCount = HUGE_VALF;
        keyAni.autoreverses = true;
        CATransform3D t1 = CATransform3DIdentity;
        t1 = CATransform3DTranslate(t1, 0, -10, 0);
        t1 = CATransform3DScale(t1, 0.9, 0.9, 1);
        CATransform3D t2 = CATransform3DIdentity;
        t2 = CATransform3DTranslate(t2, 0, 10, 0);
        t2 = CATransform3DScale(t2, 0.9, 0.9, 1);
        keyAni.values = @[[NSValue valueWithCATransform3D:t1],
                          [NSValue valueWithCATransform3D:CATransform3DIdentity],
                          /*[NSValue valueWithCATransform3D:t2]*/];
        [obj.layer addAnimation:keyAni forKey:@"ani"];
    }];
}
- (void)removeAnimation {
    
    [self.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [obj.layer removeAllAnimations];
    }];
}

- (void)touchAction:(UIControl *)sender {
    
}
@end
